﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.IO;

namespace AIMLAugmenter
{
    class Program
    {
        private static readonly string[] aimlFiles = Directory.GetFiles(".\\aiml\\", "*.aiml");

        private Program()
        {
        }

        static void Main(string[] args)
        {
            foreach (string aimlFileName in aimlFiles)
            {
                Console.Write(aimlFileName.Substring(7) + "...");

                XmlDocument xmlDoc = new XmlDocument();
                xmlDoc.Load(aimlFileName);
                XmlNodeList patNodeList = xmlDoc.GetElementsByTagName("pattern");
                string context = " * # * # * # ";
                XmlAttribute starIndexAttribute = xmlDoc.CreateAttribute("index");
                starIndexAttribute.Value = "4";

                foreach (XmlNode patNode in patNodeList)
                {
                    // augmenting pattern with the context information
                    patNode.InnerText = context + patNode.InnerText;

                    // srai update withing the patNode's parent category
                    XmlNode sraiNode;
                    sraiNode = patNode.ParentNode.SelectSingleNode("template/srai");
                    if (sraiNode != null)
                    {
                        // updating star references (count += 3, since there are 3 context stars)
                        XmlNodeList starNodes = sraiNode.SelectNodes("star");
                        foreach (XmlNode n in starNodes)
                        {
                            if (n.Attributes["index"] != null)
                            {
                                n.Attributes["index"].Value = (Int32.Parse(n.Attributes["index"].Value) + 3).ToString();
                            }
                            else
                            {
                                n.Attributes.Append(starIndexAttribute);
                            }
                        }
                        sraiNode.ParentNode.InnerXml = "<srai>" + context + sraiNode.InnerXml + "</srai>";
                    }

                    sraiNode = patNode.ParentNode.SelectSingleNode("template/sr");
                    if (sraiNode != null)
                    {
                        sraiNode.ParentNode.InnerXml = "<srai>" + context + "<star index=\"4\"/></srai>";
                    }
                }

                xmlDoc.Save("./aiml/aug/aug-" + aimlFileName.Substring(7));

                Console.WriteLine("done");
            }
        }
    }
}
